<?php

namespace app\store\controller\shop;

use app\common\model\User;
use app\store\controller\Controller;
use app\store\model\store\Shop as ShopModel;
use app\store\model\store\shop\Coach as CoachModel;
use think\Db;
use think\Session;

/**
 * 门店教练控制器
 * Class Clerk
 * @package app\store\controller\shop
 */
class Coach extends Controller
{

    /**
     * @param int $shop_id
     * @param string $search
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index($shop_id = 0, $search = '')
    {
        $use_type = $this->store['user']['user_type'];
        $model = new CoachModel();
        // 门店
        if ($use_type == 2) {
            $shop_id = $this->store['user']['shop_user_id'];
        } elseif ($use_type == 3) { // 教练
            $coach_id = $this->store['user']['shop_user_id'];
            $detail = $model->field('shop_id')->find(['coach_id' => $coach_id]);
            $shop_id = $detail['shop_id'];
        }
        // 店员列表
        $list = $model->getList(-1, $shop_id, $search);

        // 门店列表
        $shopList = ShopModel::getAllList();
        return $this->fetch('index', compact('list', 'shopList'));
    }

    /**
     * 添加店员
     * @return array|bool|mixed
     * @throws \Exception
     */
    public function add()
    {
        $model = new CoachModel();
        if (!$this->request->isAjax()) {
            // 门店列表
            $shopList=$this->shopList();
            return $this->fetch('add', compact('shopList'));
        }
        // 新增记录
        $data = $this->postData('coach');
        $user_id = $data['user_id'];//选择的用户
        if (!isset($data['user_id']) || $data['user_id'] == '') {
            return $this->renderError('请选择用户设置为教练');
        }
        if ($data['shop_id'] == '') {
            return $this->renderError('请选择所属门店');
        }
        $check = User::detail(['user_id'=>$user_id]);
        if (!$check){
            return $this->renderError('用户不存在');
        }
        if ($check['is_coach'] == 1){
            return $this->renderError('此用户已经是教练了');
        }
        $shop = Db::name('store_shop')->find($data['shop_id']);
        if (!$shop || $shop['is_delete'] != 0) {
            return $this->renderError('选择的门店不存在');
        }
        Db::startTrans();
        try {
            $coach_id = $model->add($data);
            //用户标记为教练
//            $user_id = $this->postData('coach')['user_id'];
            Db::name('user')->where(['user_id' => $user_id])->update(['is_coach' => 1]);
            //添加教练管理员
            $add['user_name'] = $data['real_name'];
            $add['real_name'] = $data['real_name'];
            $add['password'] = yoshop_hash('123456');
            $add['is_super'] = 0;
            $add['user_type'] = 3;
            $add['shop_user_id'] = $coach_id; //教练表的id
            $add['wxapp_id'] = $this->store['wxapp']['wxapp_id'];
            $add['create_time'] = time();
            $add['update_time'] = time();
            $store_user_id = Db::name('store_user')->insertGetId($add);
            //权限表
            $role_add['store_user_id'] = $store_user_id;
            $role_add['role_id'] = 10002;//门店
            $role_add['wxapp_id'] = $check['wxapp_id'];
            $role_add['create_time'] = time();
//            $role_add['update_time'] = time();
            Db::name('store_user_role')->insert($role_add);
            Db::commit();
            return $this->renderSuccess('添加成功', url('shop.coach/index'));
        }catch (\Exception $exception){
            Db::rollback();
            return $this->renderError($model->getError() ?: '添加失败');
        }
    }

    /**
     * 编辑店员
     * @param $coach_id
     * @return array|bool|mixed
     * @throws \think\exception\DbException
     */
    public function edit($coach_id)
    {
        // 店员详情
        $model = CoachModel::detail($coach_id);
        if (!$this->request->isAjax()) {
            // 门店列表
            $shopList=$this->shopList();
            return $this->fetch('edit', compact('model', 'shopList'));
        }
        // 新增记录
        if ($model->edit($this->postData('coach'))) {
            return $this->renderSuccess('更新成功', url('shop.coach/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    public function test(){
        $model = CoachModel::detail(['coach_id'=>10013]);
                if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
    }

    /**
     * 删除店员
     * @param $coach_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($coach_id)
    {
        // 店员详情
        $model = CoachModel::detail(['coach_id'=>$coach_id]);
//        if (!$model->setDelete()) {
//            return $this->renderError($model->getError() ?: '删除失败');
//        }
        Db::startTrans();
        try {
            Db::name('coach')->where(['coach_id'=>$coach_id])->update(['is_delete'=>1]);
            Db::name('store_user')->where(['shop_user_id' => $coach_id, 'user_type' => 3])->update(['is_delete' => 1, 'update_time' => time()]);
            $user_id = $model->toArray()['user_id'];
            Db::name('user')->where(['user_id' => $user_id])->update(['is_coach' => 0]);//去除教练
            Db::commit();
            return $this->renderSuccess('删除成功');
        }catch (\Exception $exception){
            Db::rollback();
            return $this->renderError($model->getError() ?: '删除失败');
        }
    }

    /**
     * // 门店列表
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function shopList(){
        $shop_id = $this->store['user']['shop_user_id'];
        $where=[];
        if ($shop_id){
            $where['shop_id']=$shop_id;
        }
        return ShopModel::getAllList($where);
    }

}